package com.xzzz.backend.bsms.server.rbac.menu;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.xzzz.common.db.aspect.Pages;
import com.xzzz.common.base.exception.XzException400;
import com.xzzz.common.base.exception.XzException404;
import com.xzzz.common.base.util.PrimaryKeyUtil;
import com.xzzz.backend.bsms.server.rbac.menu.pojo.MenuEntity;
import com.xzzz.backend.bsms.server.rbac.menu.pojo.MenuPageReq;
import com.xzzz.backend.bsms.server.rbac.menu.pojo.MenuReq;
import com.xzzz.backend.bsms.server.rbac.menu.pojo.MenuTreeRes;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 菜单信息业务接口
 */
@Slf4j
@Service
@AllArgsConstructor
public class MenuService extends ServiceImpl<MenuMapper, MenuEntity> {

    /**
     * 分页
     */
    @Pages
    public PageInfo<MenuEntity> page(MenuPageReq page) {
        return new PageInfo<>(this.listAll(page.to(MenuReq.class)));
    }

    /**
     * 全部列表
     */
    public List<MenuEntity> listAll(MenuReq req) {
        req.setDelTime(0L);
        return baseMapper.listAll(req.to(MenuEntity.class));
    }

    /**
     * 全部树状列表
     */
    public List<MenuTreeRes> listTree(MenuReq req) {
        List<MenuEntity> menuList = this.listAll(req);
        if (CollUtil.isNotEmpty(menuList)) {
            return MenuTreeUtil.treeWrap(menuList);
        }
        return new ArrayList<>();
    }

    /**
     * 根据ID查询
     */
    public MenuEntity selectById(Long id) {
        return Optional.ofNullable(baseMapper.selectOne(
                new LambdaQueryWrapper<MenuEntity>().eq(MenuEntity::getId, id))
        ).orElseThrow(() -> new XzException404("数据不存在"));
    }

    /**
     * 新增
     *
     * @param req 主体信息
     * @return 新增条数
     */
    @Transactional(rollbackFor = Exception.class)
    public Long insert(MenuReq req) {
        MenuEntity entity = req.to(MenuEntity.class);
        entity.setId(PrimaryKeyUtil.nextId());
        baseMapper.insert(entity);
        return entity.getId();
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public Long update(MenuReq req) {
        XzException404.throwBy(req.getId() == null, "ID不得为空");
        baseMapper.updById(req.to(MenuEntity.class));
        return req.getId();
    }

    /**
     * 删除
     *
     * @param id ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        XzException400.throwBy(id == null, "ID不得为空");
        baseMapper.delLogic(id, System.currentTimeMillis());
    }
}